package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.annotation.AutoFill;
import com.itheima.enumeration.OperationType;
import com.itheima.exception.DeletionNotAllowedException;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.entity.Dept;
import com.itheima.pojo.entity.Emp;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper,Dept> implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {

        return deptMapper.selectList(null);
    }

    @Override
    public void removeById(Integer id) {
        List<Emp> list = empMapper.selectList(new LambdaQueryWrapper<Emp>().in(Emp::getDeptId, id));
        if(!CollectionUtil.isEmpty(list)){
            throw new DeletionNotAllowedException("部门下有员工，不能删除！");
        }
        deptMapper.deleteById(id);
    }

    @Override
    public void saveDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        save(dept);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        updateById(dept);
    }

    @Override
    public Dept findById(Integer id) {
        Dept dept = getById(id);
        return dept;
    }
}
